package com.mcxx.modules.system.service.impl;

import com.mcxx.common.exception.BizException;
import com.mcxx.constant.MQConstant;
import com.mcxx.modules.system.service.SalvationStandardService;
import com.mcxx.modules.base.utils.QueryParamUtil;
import com.mcxx.modules.filemanage.easypoi.util.ExportExcelService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.miniSalvation.fundpay.entity.FundPayEntity;
import com.mcxx.modules.miniSalvation.fundpay.param.FundPayListSearchParam;
import com.mcxx.modules.miniSalvation.fundpay.service.read.FundPayReadService;
import com.mcxx.modules.miniSalvation.order.entity.StandardEntity;
import com.mcxx.modules.miniSalvation.order.entity.StandardHistoryEntity;
import com.mcxx.modules.miniSalvation.order.service.read.StandardHistoryReadService;
import com.mcxx.modules.miniSalvation.order.service.read.StandardReadService;
import com.mcxx.modules.miniSalvation.order.service.write.StandardWriteService;
import com.mcxx.modules.miniSalvation.welfare.dto.WelfareDTO;
import com.mcxx.modules.miniSalvation.welfare.param.WelfareFamilyParam;
import com.mcxx.modules.miniSalvation.welfare.param.WelfareParam;
import com.mcxx.modules.system.dto.MQMessageDTO;
import com.mcxx.modules.system.dto.ReissueStandardDTO;
import com.mcxx.modules.system.dto.StandardDTO;
import com.mcxx.modules.system.entity.TaskExportEntity;
import com.mcxx.modules.system.param.StandardParam;
import com.mcxx.modules.system.service.write.TaskExportWriteService;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.yinhai.ta404.component.audit.vo.ExcelInfo;
import com.yinhai.ta404.core.exception.AppException;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;


@Service
@TaTransactional
public class SalvationStandardServiceImpl implements SalvationStandardService {
    private static final Logger logger = LoggerFactory.getLogger(SalvationStandardServiceImpl.class);
    @Autowired
    private StandardReadService standardReadService;
    @Autowired
    private StandardWriteService standardWriteService;
    @Autowired
    private StandardHistoryReadService standardHistoryReadService;
    @Autowired
    private FundPayReadService fundPayReadService;
    @Autowired
    private ExportExcelService exportExcelService;
    @Autowired
    private TaskExportWriteService taskExportWriteService;
    @Autowired
    private FileService fileService;


    @Override
    public Map<String, Object> getSalvationDetail(String id){
        Map<String, Object> rstMap = new HashMap<>();

        StandardParam standardParam = new StandardParam();
        standardParam.setId(id);
        List<StandardEntity> salvationStandardList = standardReadService.getByParam(standardParam);
        StandardEntity salvationStandard = salvationStandardList.get(0);
        rstMap.put("salvationStandard", salvationStandard);


        List<StandardEntity> childStandardList =  standardReadService.querySalvationByPid(id);
        if(!childStandardList.isEmpty()){
            rstMap.put("childStandardList", childStandardList);
        }

        return rstMap;
    }


    @Override
    public String updateStandard(StandardDTO parentStandardDTO, UserAccountVo userAccountVo){



        fundPayReadService.verifyFundPayThrow(parentStandardDTO.getBusinessType(), userAccountVo.getAreaCode(),
                parentStandardDTO.getStandType(), DateUtil.sdf2.format(new Date()), null, null);


        StandardEntity standardEntity = standardReadService.selectStandardById(parentStandardDTO.getId());
        if(null == standardEntity || !Constant.StandardStatus.ENABLE.equals(standardEntity.getStatus())) {
            throw new BizException("该标准未启用");
        }


        String welfareId = Constant.getUUID();


        standardWriteService.saveStandard(parentStandardDTO, userAccountVo, welfareId);

        return null;
    }


    @Override
    public String confirmWelfareResult(String standardId, UserAccountVo userAccountVo) {
        return null;
    }


    @Override
    public void diBaoGearTrial(WelfareFamilyParam welfareFamilyParam, UserAccountVo userAccountVo) {

        QueryParamUtil.setBaseParamValue(welfareFamilyParam, userAccountVo);

    }


    @Override
    public String cancelWelfare(String standardId) {
        List<StandardHistoryEntity> list = standardHistoryReadService.selectStandardHisByStandardId(standardId, Constant.WelfareStatus.VALID);
        StandardHistoryEntity standardHistoryEntity = null;
        if(null != list && list.size() > 0) {
            standardHistoryEntity = list.get(0);
        }
        else {
            return "调标撤销失败：数据出错没有找到可以撤销的历史记录";
        }
        return null;
    }


    @Override
    public String getStandardHisByStandardId(String standardId) {
        List<StandardHistoryEntity> list = standardHistoryReadService.selectStandardHisByStandardId(standardId, Constant.WelfareStatus.VALID);
        StandardHistoryEntity standardHistoryEntity = null;
        if(null != list && list.size() > 0) {
            standardHistoryEntity = list.get(0);
        }
        return standardHistoryEntity==null ? null : standardHistoryEntity.getId();
    }



    @Override
    public ExcelInfo exportExcelWelfareTemp(WelfareParam param, UserAccountVo userAccountVo) {
        ExcelInfo excelInfo = null;
        QueryParamUtil.setBaseParamValue(param, userAccountVo);
        param.setBusinessType(Constant.BusinessCode.TEKUN);

        if(StringUtils.isNotBlank(param.getCountyCode())){

            param.setAreaCode(param.getCountyCode());
            QueryParamUtil.setBaseParamValue(param, userAccountVo);
        }
        List<WelfareDTO> welfareDTOS = new ArrayList<>();

        if(null == welfareDTOS || welfareDTOS.size() == 0) {
            throw new AppException("没有可下载数据，请先进行调标试算！");
        }
        WelfareDTO welfareDTO = welfareDTOS.get(0);
        String fileName = "调标试算记录.xls";
        String title = "调标试算家庭结果列表";
        String sheet = "调标试算";
        if(Constant.BusinessCode.DIBAO.equals(welfareDTO.getBusinessType())) {
            if(Constant.BusinessStandType.CITY_DIBAO.equals(welfareDTO.getStandType())) {
                fileName = "城市低保调标试算记录.xls";
                title = "城市低保调标试算家庭结果列表";
            }
            else {
                fileName = "农村低保调标试算记录.xls";
                title = "农村低保调标试算家庭结果列表";
            }
        }
        else {
            if(Constant.BusinessStandType.CITY_TEKUN.equals(welfareDTO.getStandType())) {
                fileName = "城市特困调标试算记录.xls";
                title = "城市特困调标试算家庭结果列表";
            }
            else {
                fileName = "农村特困调标试算记录.xls";
                title = "农村特困调标试算家庭结果列表";
            }
        }

        excelInfo = exportExcelService.exportOrgOpLogs(WelfareDTO.class, welfareDTOS,fileName, title,sheet,false);

        if(null != excelInfo){
            InputStream sbs = new ByteArrayInputStream(excelInfo.getFile());
            String objectkey = fileService.upload(sbs,excelInfo.getFileName());
            if(StringUtils.isNotBlank(objectkey)){
                TaskExportEntity taskExport = new TaskExportEntity();
                taskExport.setId(Constant.getUUID());
                taskExport.setUserid(userAccountVo.getUserId());
                taskExport.setTaskName(excelInfo.getFileName());
                taskExport.setTaskTitle("调标试算结果");
                taskExport.setParam("xls");
                taskExport.setCreateTime(new Date());
                taskExport.setFileUrl(objectkey);
                taskExport.setState("02");
                int i = taskExportWriteService.insertIgnoreNull(taskExport);
                if(i > 0){
                    excelInfo = null;
                }
            }
        }
        else {
            throw new AppException("没有可下载数据，请先进行调标试算！");
        }
        return excelInfo;
    }
}
